package com.lin.wx.official.account.controller;


import com.lin.wx.official.account.model.vo.WxBodyVO;
import com.lin.wx.official.account.service.IWxManagerBiz;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linjiang
 * @date 2024/6/19
 * @fn 微信回调管理
 */
@RestController
@RequestMapping("/wx")
public class WxCallBackController {
    @Resource
    private IWxManagerBiz wxManagerBiz;

    /**
     * 微信验签接口
     *
     * @param appId
     * @param bodyVO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{app_id}", method = RequestMethod.GET)
    public String varifyToken(@PathVariable("app_id") String appId, @ModelAttribute WxBodyVO bodyVO, HttpServletRequest request) throws Exception {

        System.out.println(request.getParameter("encrypt_type"));
        System.out.println(request.getParameter("msg_signature"));
        return wxManagerBiz.verifyToken(appId, bodyVO);
    }

    /**
     * 微信推送xml消息回调接口
     *
     * @param appId
     * @param messageXml
     * @param bodyVO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{app_id}", consumes = MediaType.TEXT_XML_VALUE, method = RequestMethod.POST)
    public String callbackXml(@PathVariable("app_id") String appId,
                              @RequestBody(required = false) String messageXml,
                              @ModelAttribute WxBodyVO bodyVO, HttpServletRequest request) throws Exception {

        System.out.println(request.getParameter("encrypt_type"));
        System.out.println(request.getParameter("msg_signature"));
        return wxManagerBiz.callbackXml(appId, messageXml, bodyVO);
    }

    /**
     * 个人账户不支持网页授权获取用户信息，因为公众号必须进行微信认证。
     * 所以，必须是企业注册的服务号。
     *
     * @param appId
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/redirect/{app_id}", method = RequestMethod.GET)
    public void redirect(@PathVariable("app_id") String appId, HttpServletResponse response) throws IOException {
        System.out.println("网页授权获取openId第一步：" + appId);
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";
        response.sendRedirect(String.format(url, appId, "http://117.72.46.242:8000/wx/getOpenId", appId));
    }

    @RequestMapping(value = "/getOpenId", method = RequestMethod.GET)
    public void getOpenId(String code, String state, HttpServletResponse response) throws Exception {
        System.out.println("网页授权获取openId第二步：" + "授权码 -> code=" + code + "公众号appId -> app_id=" + state);
        String openId = wxManagerBiz.getOpenId(code, state);
        response.sendRedirect("http://www.baidu.com/?open_id=" + openId);
    }


}
